import {matchRoutes, Navigate, useLocation, useNavigate} from "react-router-dom";
import {reactLocalStorage} from "reactjs-localstorage";
import {useEffect, useState} from "react";
import {getMenu} from "@/api/user";
import {defaulyRoutes, getRouteMenu} from "@/router/router";
import {addMenuAction} from "@/store/user";
import {useDispatch, useSelector} from "react-redux";
import {IRootReducer} from "@/store";
import {message} from "antd";

const RequireAuth = ({children,routers}: any ) => {
    const location = useLocation();
    const [user, setUser] = useState(reactLocalStorage.getObject('user', {}));
    // 监听 menu
    const menu: object = useSelector((state: IRootReducer) => {  //拿到store中的state
        return state.userReducer.menu
    })
    const mathchs = matchRoutes(routers, location);
    //  判断访问路径是否存在
    const isExist = mathchs?.some((item) => item.pathname == location.pathname);
    const navigate = useNavigate();
    // 监听用户信息和menu，变更时从新请求接口获取菜单数据
    // 用户信息变更，或刷新页面rudex中的菜单数据需要重新请求
    useEffect(() => {

        if (Object.keys(user).length == 0 && location.pathname !== '/login' ) {
            message.error("token 过期，请重新登录!");
            navigate("/login");
        }
        // 这里判断条件是：token 存在并且是匹配到路由并且是已经登录的状态
        if (Object.keys(user).length && isExist ) {
            // 如果你已经登录了，但是你通过浏览器里直接访问login的话不允许直接跳转到login路由，必须通过logout来控制退出登录或者是token过期返回登录界面
            if (location.pathname == "/" || location.pathname == "/login") {
                navigate("/index");
            } else {
                // 如果是其他路由就跳到其他的路由
                navigate(location.pathname);
            }
        }

    }, [menu, user,location])


    return children;
};

export default RequireAuth;
